<template>
	<div class="login-container">
		<div class="login-content">
			<!-- Logo区域 -->
			<div class="logo-section">
				<div class="logo">
					<van-icon name="shield-o" size="48" color="white" />
				</div>
				<h1 class="app-name">生态昆山政企通</h1>
				<p class="app-desc">企业环保管理一体化平台</p>
			</div>

			<!-- 登录状态显示 -->
			<div class="login-status" v-if="loginStatus">
				<van-loading v-if="loginStatus === 'loading'" type="spinner" size="24px">
					{{ loginMessage }}
				</van-loading>

				<div v-else-if="loginStatus === 'error'" class="error-status">
					<van-icon name="warning-o" size="24" color="#ee0a24" />
					<p>{{ loginMessage }}</p>
					<van-button type="primary" size="small" @click="retryLogin">重试</van-button>
				</div>

				<div v-else-if="loginStatus === 'success'" class="success-status">
					<van-icon name="success" size="24" color="#07c160" />
					<p>登录成功，正在跳转...</p>
				</div>
			</div>

			<!-- 登录按钮 -->
			<div class="login-actions" v-if="!loginStatus || loginStatus === 'error'">
				<van-button type="primary" block size="large" :loading="isLoggingIn" @click="startLogin"> 一键登录 </van-button>

				<p class="login-tip">
					点击登录即表示同意
					<span class="link" @click="showPrivacy">《隐私政策》</span>
					和
					<span class="link" @click="showService">《服务协议》</span>
				</p>
			</div>
		</div>

		<!-- 底部信息 -->
		<div class="footer-info">
			<p>昆山市生态环境局</p>
		</div>
	</div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useOAuthLogin } from '@/utils/oauthHandler'
import { showToast, showDialog } from 'vant'

export default {
	name: 'LoginPage',
	setup() {
		const router = useRouter()
		const route = useRoute()
		const userStore = useUserStore()
		const { handleLogin, redirectToAuth, getHandleType } = useOAuthLogin()

		const loginStatus = ref('')
		const loginMessage = ref('')
		const isLoggingIn = ref(false)

		// 处理OAuth登录回调
		const handleOAuthCallback = async () => {
			loginStatus.value = 'loading'
			loginMessage.value = '正在处理登录...'

			try {
				const result = await handleLogin()

				if (result.success) {
					loginStatus.value = 'success'
					loginMessage.value = '登录成功'

					// 跳转到目标页面或首页
					const redirect = route.query.redirect || '/'
					setTimeout(() => {
						router.replace(redirect)
					}, 1000)
				} else if (result.needSpecialHandle && result.code) {
					// 处理特殊状态码
					const handleType = getHandleType(result.code)

					if (result.code === '50001') {
						// 未绑定企业，跳转到绑定页面
						showDialog({
							title: '提示',
							message: result.msg || handleType.message,
							confirmButtonText: '去认证',
							showCancelButton: false,
						}).then(() => {
							router.replace('/company/bound')
						})
					} else if (result.code === '50002') {
						// 待审核
						showDialog({
							title: '提示',
							message: result.msg || handleType.message,
							confirmButtonText: '刷新',
							showCancelButton: false,
						}).then(() => {
							window.location.reload()
						})
					} else if (result.code === '50003') {
						// 审核未通过
						showDialog({
							title: '提示',
							message: result.msg || handleType.message,
							confirmButtonText: '我知道了',
							showCancelButton: false,
						})
					}

					loginStatus.value = 'error'
					loginMessage.value = result.msg || handleType.message
				} else if (result.needAuth) {
					// 需要OAuth授权
					await redirectToAuth()
				} else {
					loginStatus.value = 'error'
					loginMessage.value = result.error || '登录失败'
				}
			} catch (error) {
				console.error('登录处理失败:', error)
				loginStatus.value = 'error'
				loginMessage.value = '登录失败，请重试'
			}
		}

		// 开始登录流程
		const startLogin = async () => {
			try {
				isLoggingIn.value = true
				await redirectToAuth()
			} catch (error) {
				console.error('跳转授权页面失败:', error)
				showToast('登录失败，请重试')
			} finally {
				isLoggingIn.value = false
			}
		}

		// 重试登录
		const retryLogin = () => {
			loginStatus.value = ''
			loginMessage.value = ''
			startLogin()
		}

		// 显示隐私政策
		const showPrivacy = () => {
			showDialog({
				title: '隐私政策',
				message: '这里是隐私政策的内容...',
				confirmButtonText: '我知道了',
			})
		}

		// 显示服务协议
		const showService = () => {
			showDialog({
				title: '服务协议',
				message: '这里是服务协议的内容...',
				confirmButtonText: '我知道了',
			})
		}

		// 页面加载时检查是否有OAuth回调
		onMounted(() => {
			const urlParams = new URLSearchParams(window.location.search)
			const code = urlParams.get('code')

			if (code) {
				// 有code参数，处理OAuth回调
				handleOAuthCallback()
			} else {
				// 检查是否已经登录
				userStore.loadFromCache()
				if (userStore.isAuthenticated) {
					const redirect = route.query.redirect || '/'
					router.replace(redirect)
				}
			}
		})

		return {
			loginStatus,
			loginMessage,
			isLoggingIn,
			startLogin,
			retryLogin,
			showPrivacy,
			showService,
		}
	},
}
</script>

<style lang="less" scoped>
.login-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	flex-direction: column;
	position: relative;
}

.login-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 40px 20px;
}

.logo-section {
	text-align: center;
	margin-bottom: 60px;
}

.logo {
	width: 80px;
	height: 80px;
	border-radius: 16px;
	margin: 0 auto 20px auto;
	background: rgba(255, 255, 255, 0.2);
	display: flex;
	align-items: center;
	justify-content: center;
	backdrop-filter: blur(10px);
	border: 1px solid rgba(255, 255, 255, 0.3);
}

.app-name {
	font-size: 28px;
	font-weight: 600;
	color: white;
	margin: 0 0 12px 0;
}

.app-desc {
	font-size: 16px;
	color: rgba(255, 255, 255, 0.8);
	margin: 0;
}

.login-status {
	margin-bottom: 40px;
	text-align: center;
	min-height: 60px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.error-status,
.success-status {
	color: white;

	p {
		margin: 12px 0 16px 0;
		font-size: 16px;
	}
}

.login-actions {
	width: 100%;
	max-width: 320px;
}

.login-tip {
	text-align: center;
	font-size: 12px;
	color: rgba(255, 255, 255, 0.7);
	margin: 16px 0 0 0;
	line-height: 1.4;
}

.link {
	color: rgba(255, 255, 255, 0.9);
	text-decoration: underline;
	cursor: pointer;
}

.footer-info {
	text-align: center;
	padding: 20px;
	color: rgba(255, 255, 255, 0.6);
	font-size: 14px;
}

:deep(.van-button--large) {
	height: 50px;
	border-radius: 25px;
	font-size: 18px;
	font-weight: 600;
}

:deep(.van-loading__text) {
	color: white;
	margin-top: 12px;
}
</style>